var ns, WXPhotoPicker;
app = new Vue({
    el: '#app',
    data: {
        ServiceID: 0,//业务ID
        projectid:0,//传输的项目ID
        newform: {
            ID: 0,
            ProjectID: 0,
            ProjectName: '',
            DeviceID: 0,//设备
            DeviceName: '',
            DeviceIDs: [],
            FromType: 0,//来源
            FromTypeName: '',
            Type: 1,//维修类型
            TypeName: '',
            WriteName: '',//报修人姓名
            WriteDate: '',
            ServiceContent: '',
            IsFromCustomer: false,//是否来自客服工单
            CustomerServiceID: 0,
            ImgDeleteIDs: [],
            action: 'savedeviceservice'
        },
        ID: 0,
        imglist: [],
        ProjectList: [],
        maxuploadcount: CONFIG.maxuploadcount,
        //工单来源
        IsOrderSourceOpen: false,
        OrderSourceList: [
            { ID: 1, Name: '设备维保', },
            { ID: 2, Name: '设备巡检', },
            { ID: 3, Name: '维修登记', },
            { ID: 4, Name: '客服工单', },
        ],
        //维修类型
        IsRepairTypelOpen: false,
        RepairTypeList: [
            { ID: 1, Name: '一般维修', },
            { ID: 2, Name: '重大维修', },
        ],
    },
    methods: {
        get_data: function () {
            var that = this;
            var options = {
                action: 'getqualitycontrolparams'
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.ProjectList = data.list;
                    if (data.list.length > 0 && that.ID <= 0) {
                        if(that.projectid<=0){
                            that.newform.ProjectID = data.list[0].ID;
                            that.newform.ProjectName = data.list[0].Name;
                        }
                        //判断是否传了projectid 项目ID
                        if(that.projectid>0){
                            var resultIndex=that.ProjectList.findIndex((val)=>{
                                return val.ID==that.projectid;
                            });
                            var findIndex=resultIndex>-1?resultIndex:0;
                            that.newform.ProjectID =that.ProjectList[findIndex].ID;
                            that.newform.ProjectName = that.ProjectList[findIndex].Name;
                        }
                        if(that.newform.FromType<=0){
                            that.doSelectOrderSource(that.OrderSourceList[0]);
                        }
                        that.doSelectRepairType(that.RepairTypeList[0]);
                    }
                    //加载下拉列表数据
                    that.initPicker();
                }
            });
        },
        do_save: function () {
            var that = this;
            if (that.newform.ProjectID <= 0) {
                api.toast({
                    msg: '请选择项目',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.FromType <= 0) {
                api.toast({
                    msg: '请选择工单来源',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.Type == '') {
                api.toast({
                    msg: '请选择维修类型',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.WriteName == '') {
                api.toast({
                    msg: '请填写报修人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.ServiceContent == '') {
                api.toast({
                    msg: '请填写问题描述',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            that.do_save_process();
        },
        do_save_process: function () {
            var that = this;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            // console.log(JSON.stringify(that.newform));
            ns.post(that.newform, function (succeed, data, err) {
                // console.log(JSON.stringify(succeed));
                // console.log(JSON.stringify(data));
                // console.log(JSON.stringify(err));
                if (succeed) {
                    if (data.status) {
                        api.toast({
                            msg: '操作成功',
                            duration: 2000,
                            location: 'bottom'
                        });
                        api.sendEvent({
                            name: 'reloadrepairlist',
                        });
                        setTimeout(function () {
                            api.closeWin();
                        }, 300)
                        return
                    }
                    else if (data.Msg) {
                        api.toast({
                            msg: data.Msg,
                            duration: 3000,
                            location: 'bottom'
                        });
                    }

                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        //上传图片
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    that.do_imageFilter(ret.data);
                    // that.imglist.push({
                    //     ID: 0,
                    //     url: ret.data,
                    //     thumbPath: ret.data,
                    //     isupload: true
                    // });
                } 
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.do_imageFilter(item.path);
                            // that.imglist.push({
                            //     ID: 0,
                            //     url: item.path,
                            //     thumbPath: item.path,
                            //     isupload: true
                            // });
                        });
                    }
                }
            });
        },
         //图片压缩
         do_imageFilter:function(path){
            var that=this;
            var imgName = Date.now() + '.jpg';
            var target_w = 500;
            var imageFilter = api.require('imageFilter');
            imageFilter.getAttr({
                path: path
            }, function(ret, err) {
                if (ret.status) {
                    if (ret.width < target_w) {
                        target_w = ret.width;
                    }
                    var original_w = ret.width;
                    var original_h = ret.height;
                    var scale = original_w / target_w;
                    var target_h = Math.round(original_h / scale);
                    imageFilter.compress({
                        img: path,
                        quality: 1,
                        size: {
                            w: target_w,
                            h: target_h
                        },
                        save: {
                            album: false,
                            imgPath: api.cacheDir + '/upload/',
                            imgName: imgName
                        }
                    }, function(ret, err) {
                        if (ret.status) {
                            var imgFullName=api.cacheDir + '/upload/' + imgName;
                            that.imglist.push({
                                ID: 0,
                                url: imgFullName,
                                thumbPath: imgFullName,
                                isupload: true
                            });
                        }else{
                            alert( JSON.stringify( err ) );
                        }
                    });
                }
            });
        },
        remove_img: function (index,item) {
            var that = this;
            that.imglist.splice(index, 1);
        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }

            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        doChooseUser: function (item) {
            var that = this;
            if (item.length > 0) {
                that.newform.InChargeUserID = item[0].id;
                that.newform.UserName = item[0].text;
            }
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    // 选择项目
                    var pickerProject = new $.PopPicker({
                        layer: 1,
                        fileID: 'ID',
                        fileName: 'Name',
                    });
                    var projectData = _this.ProjectList || [];
                    pickerProject.setData(projectData);
                    var showProjectPickerButton = doc.getElementById('chooseproject');
                    showProjectPickerButton.addEventListener('click', function (event) {
                        pickerProject.show(function (items) {
                            _this.newform.ProjectID = items[0].value;
                            _this.newform.ProjectName = items[0].text;
                            _this.setData();//切换项目后的操作
                            //返回 false 可以阻止选择框的关闭
                            //return false;
                        });
                    }, false);
                });
            })(mui, document);
        },
        //设备选择清空
        setData() {
            var that = this;
            that.newform.DeviceID = 0;
            that.newform.DeviceName = "";
            that.newform.DeviceIDs = [];
        },
        //选择设备
        do_choose_device: function () {
            var that = this;
            ns.openWin('equipment_devicelist_frm', '选择设备', {
                projectid: that.newform.ProjectID
            });
        },
        //选择工单来源
        doOrderSourceOpen: function (id) {
            var that = this;
            that.IsOrderSourceOpen = true;
        },
        doCloseOrderSource: function () {
            var that = this;
            that.IsOrderSourceOpen = false;
        },
        doSelectOrderSource: function (item) {
            var that = this;
            that.IsOrderSourceOpen = false;
            that.newform.FromType = item.ID;
            that.newform.FromTypeName = item.Name;
        },
        //选择维修类型
        doRepairTypeOpen: function () {
            var that = this;
            that.IsRepairTypelOpen = true;
        },
        doCloseRepairType: function () {
            var that = this;
            that.IsRepairTypelOpen = false;
        },
        doSelectRepairType: function (item) {
            var that = this;
            that.IsRepairTypelOpen = false;
            that.newform.Type = item.ID;
            that.newform.TypeName = item.Name;
        },
        initPickerTime: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    var btn = document.querySelector('#choosedatetime');
                    btn.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            if (_this.newform.WriteDate) {
                                _self.picker.setSelectedValue(_this.newform.WriteDate);//回显
                            }
                            _self.picker.show(function (rs) {
                                _this.newform.WriteDate = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            if (_this.newform.WriteDate) {
                                _self.picker.setSelectedValue(_this.newform.WriteDate);//回显
                            }
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.newform.WriteDate = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);

                });
            })(mui, document);
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    WXPhotoPicker = api.require('WXPhotoPicker');
    app.ID = api.pageParam.ID || 0;
    app.ServiceID = api.pageParam.ServiceID || 0;
    var ServiceName = api.pageParam.ServiceName || '';
    app.projectid = api.pageParam.ProjectID || 0;
    var loginusername = api.getPrefs({
        sync: true,
        key: 'loginname'
    });

    app.newform.CustomerServiceID = app.ServiceID||0;
    app.newform.FromType = api.pageParam.SourceType || 0;
    if (app.newform.FromType > 0) {
        let result = app.OrderSourceList.findIndex((item) => {
            return item.ID == app.newform.FromType;
        });
        if (result > -1) {
            app.doSelectOrderSource(app.OrderSourceList[result]);
        }
    }
    //客服工单-新增整改工单
    if (app.ServiceID > 0 && app.newform.FromType == 4) {
        app.newform.IsFromCustomer = true;
    }
     //设备工单-新增维修工单
    if (app.ServiceID > 0 && (app.newform.FromType == 1||app.newform.FromType == 2)) {
        app.newform.DeviceID = app.ServiceID ;
        app.newform.DeviceName = ServiceName;
        var DeviceIDs = [];
        DeviceIDs.push(app.ServiceID);
        app.newform.DeviceIDs = DeviceIDs;
    }
    if (app.ID <= 0) {
        app.newform.WriteDate = moment().format('YYYY/MM/DD HH:mm');
        app.newform.WriteName = loginusername;
    }
    app.initPickerTime();
    app.get_data();

    api.addEventListener({
        name: 'do_choose_device_done'
    }, function (ret, err) {
        app.newform.DeviceID = ret.value.id;
        app.newform.DeviceName = ret.value.name;
        var DeviceIDs = [];
        DeviceIDs.push(ret.value.id);
        app.newform.DeviceIDs = DeviceIDs;
    });

};
